import {
	inBrowser
} from './basic.js';
import {
	onDeactivated,
	onBeforeUnmount
} from 'vue';
import {
	onMountedOrActivated
} from './onMountedOrActivated.js';

// @Experimental
export function useVisibilityChange(target, onChange) {
	// compatibility: https://caniuse.com/#feat=intersectionobserver
	if (!inBrowser || !window.IntersectionObserver) {
		return;
	}

	const observer = new IntersectionObserver(
		(entries) => {
			let inparam = entries[0].intersectionRatio > 0;
			onChange(inparam);
		}, {
			root: document.body
		},
	);

	const observe = () => {
		if (target.value) {
			observer.observe(target.value);
		}
	};

	const unobserve = () => {
		if (target.value) {
			observer.unobserve(target.value);
		}
	};

	onDeactivated(unobserve);
	onBeforeUnmount(unobserve);
	onMountedOrActivated(observe);
}